package com.longcai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.longcai.bean.PageHelper;
import com.longcai.entity.sys.SysRole;
import com.longcai.entity.sys.SysRolePermission;
import com.longcai.entity.sys.SysRoleUser;
import com.longcai.mapper.SysRoleMapper;
import com.longcai.mapper.SysRolePermissionMapper;
import com.longcai.mapper.SysRoleUserMapper;
import com.longcai.page.table.PageTableResponse;
import com.longcai.service.SysRoleService;
import com.longcai.vo.SysRoleVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ZJ
 * @since 2019-03-16
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    private static final Logger loggger = LoggerFactory.getLogger(SysRoleServiceImpl.class);

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Override
    public List<SysRole> sysRoleList() {
        return this.sysRoleMapper.selectList(null);
    }

    @Override
    public List<SysRole> listByUserId(Long userId) {
        return this.sysRoleMapper.listByUserId(userId);
    }

    @Override
    public PageTableResponse rolesList(SysRole sysRole, PageHelper pageHelper) {
        Page<SysRole> page = new Page<SysRole>(pageHelper.getStart(), pageHelper.getLength());
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(sysRole.getName())) {
            queryWrapper.eq("name", sysRole.getName());
        }

        IPage<SysRole> sysRoleIPage = this.sysRoleMapper.selectPage(page, queryWrapper);
        PageTableResponse pageTableResponse = new PageTableResponse(sysRoleIPage.getTotal(),
                sysRoleIPage.getTotal(), sysRoleIPage.getRecords());

        return pageTableResponse;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRole(SysRoleVo sysRoleVo) {
        SysRole sysRole = sysRoleVo;
        List<Integer> permissionIds = sysRoleVo.getPermissionIds();
        // 删除第一个公共菜单
        permissionIds.remove(0);
        if (sysRoleVo.getId() == null) {
            // 新增
            this.saveRole(sysRole, permissionIds);
        } else {
            // 更新
            this.updateRole(sysRole, permissionIds);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSysRole(Integer roleId) {
        QueryWrapper<SysRolePermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("roleId", roleId);
        // 删除权限角色中间表
        this.sysRolePermissionMapper.delete(queryWrapper);
        // 删除用户角色中间表
        QueryWrapper<SysRoleUser> wrapper = new QueryWrapper<>();
        wrapper.eq("roleId", roleId);
        this.sysRoleUserMapper.delete(wrapper);
        // 删除角色
        this.sysRoleMapper.deleteById(roleId);

        loggger.debug("删除角色id:{}", roleId);

    }

    private void saveRole(SysRole sysRole, List<Integer> permissionIds) {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", sysRole.getName());
        SysRole r = this.sysRoleMapper.selectOne(queryWrapper);
        if (r != null) {
            throw new IllegalArgumentException(sysRole.getName() + "已存在");
        }

        this.sysRoleMapper.insert(sysRole);
        if (!CollectionUtils.isEmpty(permissionIds)) {
            this.sysRolePermissionMapper.saveRolePermission(sysRole.getId(), permissionIds);
        }
        loggger.debug("新增角色{}", sysRole.getName());
    }

    private void updateRole(SysRole sysRole, List<Integer> permissionIds) {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", sysRole.getName());
        SysRole r = this.sysRoleMapper.selectOne(queryWrapper);
        if (r != null && !r.getId().equals(sysRole.getId())) {
            throw new IllegalArgumentException(sysRole.getName() + "已存在");
        }

        this.sysRoleMapper.updateById(sysRole);

        this.sysRolePermissionMapper.deleteById(sysRole.getId());
        if (!CollectionUtils.isEmpty(permissionIds)) {
            this.sysRolePermissionMapper.saveRolePermission(sysRole.getId(), permissionIds);
        }
        loggger.debug("修改角色{}", sysRole.getName());
    }
}
